package com.yinhai.message.core.util;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * HTTP的线程池
 *
 * @author lins0
 * @create 2017-03-28 20:30
 **/
public class HttpPoolManager {

    public static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;

    private static HttpPoolManager httpPoolManager = null;
    private static Lock locker =  new ReentrantLock();

    private int maxTotal = 50;

    private int defaultMaxPerRoute = 25;

    private HttpPoolManager(){
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    }

    public static HttpPoolManager getInstance(){
        if(httpPoolManager == null) {
            locker.lock();
            if (httpPoolManager == null) {
                httpPoolManager = new HttpPoolManager();
            }
            locker.unlock();
        }
        return httpPoolManager;
    }

    public static CloseableHttpClient getHttpClient(){

        return HttpClients.custom().setConnectionManager(getInstance().poolingHttpClientConnectionManager).build();
    }
}
